<?php
class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			 array('allow',  // allow all users to perform 'register' 
				'actions'=>array('register','resetPassword'),
				'users'=>array('guest'),
			),
				array('allow',  // allow all users to perform 'register'
						'actions'=>array('activate'),
						'users'=>array('*'),
				),
		 	array('allow', // allow authenticated user to perform 'profile' action
				'actions'=>array('profile','updateProfile','changePassword'),
				'users'=>array('@'),
			), 
			array('allow', // allow admin user to perform all actions
				'actions'=>array('admin','delete','index','create','update','view'),
				'roles'=>array('admin'),
			),
			
			
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User('create');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->validate())
			{
 			$model->password=crypt($model->password,CRYPT_BLOWFISH);
 			$model->password_repeat=crypt($model->password_repeat,CRYPT_BLOWFISH);
 			$model->createddate = new CDbExpression('NOW()');
			if($model->save()){
				$auth = Yii::app()->authManager;
				$auth->assign(Role::model()->findByPk($model->role_id)->description,$model->id);
				$this->redirect(array('view','id'=>$model->id));
			}
		}
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$oldPass = $model->password;
		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
// 			$model->password=crypt($model->password,CRYPT_BLOWFISH);
			$model->password = $oldPass;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$user = $this->loadModel($id);
		$authAss = Authassignment::model()->findByAttributes(array('userid'=>$user->id));
		$authAss->delete();
		$user->delete();
		

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	
	
	public function actionRegister()
	{ 
		
		$model=new User('register');
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->isactive=0;
			if($model->validate())
			{
			$model->password=crypt($model->password,CRYPT_BLOWFISH);
			$model->password_repeat=crypt($model->password_repeat,CRYPT_BLOWFISH);
			$model->role_id=2;
			$model->createddate = new CDbExpression('NOW()');
			$model->activekey = crypt(microtime().$model->password,CRYPT_BLOWFISH);
			if($model->save()){
				$auth = Yii::app()->authManager;
				$auth->assign(Role::model()->findByPk($model->role_id)->description,$model->id);// display the login form
				$activation_url = $this->createAbsoluteUrl('/user/activate',array("activekey" => $model->activekey, "uid" => $model->id));
				
				$name='=?UTF-8?B?'.base64_encode(Yii::app()->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode('Activation Code').'?=';
				$headers="From: ".Yii::app()->name."<".Yii::app()->params['adminEmail'].">\r\n".
						"Reply-To: ".Yii::app()->params['adminEmail']."\r\n".
						"MIME-Version: 1.0\r\n".
						"Content-Type: text/plain; charset=UTF-8";
				$body='thank you for registering for '.Yii::app()->name.', please go to < '.$activation_url.' > to activate your account.';
				mail($model->email,$subject,$body,$headers);
				
				Yii::app()->user->setFlash('register','register.success');
				$this->refresh();
				
				/* unset($_GET['userLogin']);
				unset($_GET['userName']);
				unset($_GET['password']);
				$_GET['userLogin']='true';
				$_GET['userName']= $model->username ;
				$_GET['password']=$_POST['User']['password'];
				
				$this->redirect(array('/site/login', $_GET)); */
			}
		}
		}
		
		$this->render('register',array(
				'model'=>$model,
		));
		
		
	}
	
	/**
	 * Activation user account
	 */
	public function actionActivate () {
		$uid = $_GET['uid'];
		$activekey = $_GET['activekey'];
		if ($uid&&$activekey) {
			$model=$this->loadModel($uid);
			
		if(isset($model->activekey) && ($model->activekey==$activekey)) {
				$model->isactive= 1;
				$model->save();
				Yii::app()->user->setFlash('activate.success','You account is activated successfully.');
			} else {
				Yii::app()->user->setFlash('activate.error','Incorrect activation URL.');
			}
		} else {
			Yii::app()->user->setFlash('activate.error','Incorrect activation URL.');
		}
		
		$this->render('activate',array(
				'model'=>$model,
		));
	}
	
	public function actionProfile()
	{
	
			$this->render('profile',array(
					'model'=>$this->loadModel(Yii::app()->user->id),
			));
				
		
	}
	
	public function actionUpdateProfile()
	{	
		$id = Yii::app()->user->id;
		$model=new User('updateProfile');
		$model=$this->loadModel($id);
 		$oldEmail = $model->email;
		// Uncomment the following line if AJAX validation is needed
// 		$this->performAjaxValidation($model);
	
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			// 			$model->password=crypt($model->password,CRYPT_BLOWFISH);
			if($model->email != $oldEmail){
				// deactivate user and send activation URL
				$model->isactive = 0;
				$model->activekey = crypt(microtime().$model->password,CRYPT_BLOWFISH);
			}
			if($model->save()){
				if($model->isactive ==1){
					Yii::app()->user->setFlash('message','Profile updated successfully.');
					$this->redirect(array('profile'));
				}else{
					$activation_url = $this->createAbsoluteUrl('/user/activate',array("activekey" => $model->activekey, "uid" => $model->id));
					
					$name='=?UTF-8?B?'.base64_encode(Yii::app()->name).'?=';
					$subject='=?UTF-8?B?'.base64_encode('Activation Code').'?=';
					$headers="From: ".Yii::app()->name."<".Yii::app()->params['adminEmail'].">\r\n".
							"Reply-To: ".Yii::app()->params['adminEmail']."\r\n".
							"MIME-Version: 1.0\r\n".
							"Content-Type: text/plain; charset=UTF-8";
					$body='Due to changing your email, your account is temporarily deactivated, please go to < '.$activation_url.' > to reactivate your account.';
					mail($model->email,$subject,$body,$headers);
					Yii::app()->user->setFlash('updateProfile.deactivate','Profile updated successfully, due to changing your email, your account is temporarily deactivated,check your email to reactivate it');
					//$this->redirect(array('/site/login'));
					$this->refresh();
					
				}
				
		}
	}
	
	$this->render('updateProfile',array(
			'model'=>$model,
	));
	}
	
	public function actionChangePassword()
	{
		$model=new User('changePassword');
		$id = Yii::app()->user->id;
		$user=$this->loadModel($id);
			if(isset($_POST['User'])){
				$model->attributes=$_POST['User'];
				if($model->validate())
				{	
					$oldPassword=$model->password;
					$newPassword=$model->newPassword;
					$confirmPassword=$model->confirmPassword;
					if($user->password == crypt($oldPassword,CRYPT_BLOWFISH)){
						if($newPassword==$confirmPassword){
							$user->password = crypt($newPassword,CRYPT_BLOWFISH);
							if($user->save()){
								Yii::app()->user->setFlash('message',Yii::t('user_messages','passward.change.success'));
								$this->redirect(array('profile'));
							}
						}else{
							$model->addError('confirmPassword',Yii::t('user_messages','passward.change.error'));
						}
					}else {
		
						//Yii::app()->user->setFlash('error','Password entered is incorrect.');
						$model->addError('password',Yii::t('user_messages','passward.change.error2'));
					}
				
			}	
		}
		
		$this->render('changePassword',array(
			'model'=>$model,
		));
		
	}
	
	public function actionResetPassword()
	{
		$model=new User('resetPassword');
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if(($model->username!=null && $model->username!="") || ($model->email!=null && $model->email!=""))
			{
			$user=User::model()->find('LOWER(username)=?',array(strtolower($model->username)));
			if($user===null)
				$user=User::model()->find('LOWER(email)=?',array(strtolower($model->username)));
			
			if($user!=null){
				$generatedPW= $this->generateRandomString();
			//	$this->DTC($generatedPW);
			$user->password=crypt($generatedPW,CRYPT_BLOWFISH);
				
				if($user->save()){
					
					$name='=?UTF-8?B?'.base64_encode(Yii::app()->name).'?=';
					$subject='=?UTF-8?B?'.base64_encode('Password Reset').'?=';
					$headers="From: ".Yii::app()->name."<".Yii::app()->params['adminEmail'].">\r\n".
							"Reply-To: ".Yii::app()->params['adminEmail']."\r\n".
							"MIME-Version: 1.0\r\n".
							"Content-Type: text/html; charset=UTF-8";
					$body='<div> You have requested to reset your password, this is your account information:</div><div>username : '.$user->username.'</div><div>email : '.$user->email.'</div><div>new password : '.$generatedPW.'<div>';
					mail($user->email,$subject,$body,$headers);
					
				Yii::app()->user->setFlash('reset.success',Yii::t('user_messages','reset.success.message'));
				$this->refresh();
				}
			}else{

				$model->addError('username',Yii::t('user_messages','Invalid username or email.'));
			}
			}else{
				
				$model->addError('username',Yii::t('user_messages','Username or email cannot be blank.'));
			}
				
		}
	
		$this->render('resetPassword',array(
				'model'=>$model,
		));
	}
	
	

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function generateRandomString($length = 10) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
	
	public function DTC($data) {
		if(is_array($data))
			{
				echo("<script>console.log('PHP: ".implode(',', $data)."');</script>");
			} else {
				echo("<script>console.log('PHP: ".$data."');</script>");
			}
	}
}
